<script setup lang="ts">
import { ref } from 'vue';
import debounce from 'lodash/debounce';
import { fetchRecentGames } from '@/service/api';
import { useAuthStore } from '@/store/modules/auth';

defineOptions({
  name: 'RecentGamesCard'
});

const authStore = useAuthStore();

// 临时扩展UserGame类型以支持pic属性，待后端类型同步后可移除
interface UserGameWithPic extends Api.Game.UserGame {
  pic?: string;
}

const recentGames = ref<UserGameWithPic[]>([]);
const loading = ref(false);

// 格式化游戏时长
const formatPlayTime = (minutes: number) => {
  const hours = Math.floor(minutes / 60);
  const mins = minutes % 60;
  if (hours > 0) {
    return `${hours}小时${mins}分钟`;
  }
  return `${mins}分钟`;
};

// 格式化最近游玩时间
const formatLastPlayed = (dateString: string) => {
  const date = new Date(dateString);
  const now = new Date();
  const diff = now.getTime() - date.getTime();
  const days = Math.floor(diff / (1000 * 60 * 60 * 24));

  if (days === 0) {
    return '今天';
  } else if (days === 1) {
    return '昨天';
  } else if (days < 7) {
    return `${days}天前`;
  }
  return date.toLocaleDateString();
};

// 获取最近游玩游戏
const loadRecentGames = async () => {
  if (!authStore.userInfo.userId) return;

  loading.value = true;
  try {
    const { data } = await fetchRecentGames(authStore.userInfo.userId, 6);
    console.log('recentGames 数据:', data);
    if (data) {
      recentGames.value = data;
    }
  } catch (error) {
    console.error('获取最近游玩游戏失败:', error);
  } finally {
    loading.value = false;
  }
};

const debouncedLoadRecentGames = debounce(loadRecentGames, 800, { leading: true, trailing: false });

// 移除点击跳转逻辑，不做任何处理

// 新增 getCoverUrl 方法
function getCoverUrl(game: UserGameWithPic) {
  if (game && game.pic) {
    const base = game.pic.endsWith('/') ? game.pic : `${game.pic}/`;
    return `${base}assets/main/game-logo.svg`;
  }
  return '';
}

// 新增跳转方法
function goToGame(game: UserGameWithPic) {
  if (game && game.pic) {
    const base = game.pic.endsWith('/') ? game.pic : `${game.pic}/`;
    window.open(`${base}index.html`, '_blank');
  }
}

// 初始化
loadRecentGames();
</script>

<template>
  <NCard :bordered="false" class="card-wrapper">
    <div class="card-gradient-bar"></div>
    <template #header>
      <div class="flex items-center justify-between">
        <div class="flex items-center space-x-3">
          <div class="header-icon">
            <SvgIcon icon="mdi:history" />
          </div>
          <span class="text-20px text-gray-800 font-bold">最近游玩</span>
        </div>
        <NButton text size="small" class="refresh-btn" :disabled="loading" @click="debouncedLoadRecentGames">
          <template #icon>
            <SvgIcon icon="mdi:refresh" />
          </template>
          刷新
        </NButton>
      </div>
    </template>

    <NSpin :show="loading">
      <div v-if="recentGames.length > 0" class="games-grid">
        <div v-for="game in recentGames" :key="game.id" class="game-card" @click="goToGame(game)">
          <div class="game-content">
            <!-- 游戏头部信息 -->
            <div class="game-header">
              <div class="game-icon">
                <img :src="getCoverUrl(game)" :alt="game.gameName" class="game-image" />
                <div class="game-icon-glow"></div>
              </div>
              <div class="game-info">
                <h4 class="game-title">{{ game.gameName }}</h4>
                <p class="game-category">{{ game.gameCategory }}</p>
              </div>
              <div class="play-indicator">
                <SvgIcon icon="mdi:play-circle" />
              </div>
            </div>

            <!-- 游戏统计数据 -->
            <div class="game-stats">
              <div class="stat-row">
                <span class="stat-label">游玩次数</span>
                <span class="stat-value">{{ game.playCount }}次</span>
              </div>
              <div class="stat-row">
                <span class="stat-label">游戏时长</span>
                <span class="stat-value">{{ formatPlayTime(game.playTime) }}</span>
              </div>
              <div class="stat-row">
                <span class="stat-label">最近游玩</span>
                <span class="stat-value">{{ formatLastPlayed(game.lastPlayed) }}</span>
              </div>
            </div>

            <!-- 悬停效果 -->
            <div class="game-overlay">
              <div class="play-button">
                <SvgIcon icon="mdi:play" />
              </div>
            </div>
          </div>
        </div>
      </div>

      <div v-else class="empty-state">
        <div class="empty-icon">
          <SvgIcon icon="mdi:gamepad-off" />
        </div>
        <p class="empty-text">暂无最近游玩记录</p>
        <p class="empty-subtext">开始游戏，记录你的精彩时刻</p>
      </div>
    </NSpin>
  </NCard>
</template>

<style scoped>
.card-wrapper {
  border-radius: 16px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
  padding: 12px 0;
  position: relative;
  overflow: hidden;
}

.card-wrapper:hover {
  transform: translateY(-4px);
  box-shadow: 0 16px 48px rgba(0, 0, 0, 0.12);
}

.card-wrapper::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, #667eea, #764ba2, #f093fb, #f5576c);
  background-size: 400% 100%;
  animation: gradient-shift 3s ease-in-out infinite;
}

.card-gradient-bar {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 4px;
  background: linear-gradient(90deg, #667eea, #764ba2, #f093fb, #f5576c);
  border-radius: 16px 16px 0 0;
  z-index: 2;
  pointer-events: none;
}

@keyframes gradient-shift {
  0%,
  100% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
}

.header-icon {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  color: white;
  font-size: 20px;
}

.refresh-btn {
  color: #667eea;
  font-weight: 500;
  transition: all 0.3s ease;
}

.refresh-btn:hover {
  color: #764ba2;
  transform: scale(1.05);
}

.games-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 12px;
  padding: 8px 0;
}

.game-card {
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  border-radius: 12px;
}

.game-card:hover {
  transform: translateY(-6px);
}

.game-content {
  position: relative;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  padding: 12px 10px;
  color: white;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
}

.game-content::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(45deg, rgba(255, 255, 255, 0.1) 0%, transparent 50%, rgba(255, 255, 255, 0.05) 100%);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.game-content:hover::before {
  opacity: 1;
}

.game-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 10px;
}

.game-icon {
  position: relative;
  width: 36px;
  height: 36px;
  border-radius: 16px;
  overflow: hidden;
  background: rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.game-icon:hover {
  transform: scale(1.1) rotate(5deg);
}

.game-image {
  width: 22px;
  height: 22px;
  object-fit: cover;
  border-radius: 8px;
}

.game-icon-glow {
  position: absolute;
  inset: -2px;
  background: linear-gradient(45deg, #f093fb, #f5576c, #4facfe, #00f2fe);
  border-radius: 16px;
  opacity: 0;
  transition: opacity 0.3s ease;
  z-index: -1;
}

.game-icon:hover .game-icon-glow {
  opacity: 0.3;
}

.game-info {
  flex: 1;
  min-width: 0;
}

.game-title {
  font-size: 13px;
  font-weight: 600;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.game-category {
  font-size: 12px;
  opacity: 0.8;
  font-weight: 500;
}

.play-indicator {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  font-size: 16px;
  transition: all 0.3s ease;
}

.game-content:hover .play-indicator {
  transform: scale(1.2);
  background: rgba(255, 255, 255, 0.3);
}

.game-stats {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.stat-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4px 6px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
  font-size: 12px;
}

.stat-row:hover {
  background: rgba(255, 255, 255, 0.2);
  transform: translateX(4px);
}

.stat-label {
  font-size: 12px;
  opacity: 0.8;
  font-weight: 500;
}

.stat-value {
  font-size: 12px;
  font-weight: 600;
  color: #fff;
}

.game-overlay {
  position: absolute;
  inset: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.3);
  opacity: 0;
  transition: all 0.3s ease;
  border-radius: 20px;
}

.game-content:hover .game-overlay {
  opacity: 1;
}

.play-button {
  width: 60px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 50%;
  font-size: 24px;
  color: #667eea;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
  transition: all 0.3s ease;
}

.play-button:hover {
  transform: scale(1.1);
  background: white;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.empty-icon {
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.1), rgba(118, 75, 162, 0.1));
  border-radius: 50%;
  margin-bottom: 20px;
  font-size: 40px;
  color: #667eea;
}

.empty-text {
  font-size: 18px;
  font-weight: 600;
  color: #4a5568;
  margin-bottom: 8px;
}

.empty-subtext {
  font-size: 14px;
  color: #718096;
  opacity: 0.8;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .games-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .game-content {
    padding: 8px 4px;
  }

  .game-header {
    gap: 12px;
    margin-bottom: 16px;
  }

  .game-icon {
    width: 50px;
    height: 50px;
  }

  .game-image {
    width: 32px;
    height: 32px;
  }

  .game-title {
    font-size: 12px;
  }

  .stat-row {
    padding: 6px 10px;
  }
}
</style>
